/**
 * File: ConcurrentMatchHandler.java
 * Created by: mhaimel
 * Created on: 22 Jul 2009
 * CVS:  $Id: ConcurrentMatchHandler.java,v 1.3 2009/12/07 09:37:45 mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.loader.impl;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.atomic.AtomicReference;

import uk.ac.ebi.curtain.utils.concurrent.UtilsCollect;

/**
 * @author mhaimel
 *
 */
public class ConcurrentMatchHandler {

	private final AtomicReference<ConcurrentMap<String, Set<String>>> refMap = 
		new AtomicReference<ConcurrentMap<String,Set<String>>>(
				UtilsCollect.newConcurrentMap(new ConcurrentHashMap<String, Set<String>>(0)));
	
//	private final ConcurrentSkipListMap<String, Integer> ctgIdx = new ConcurrentSkipListMap<String, Integer>();
//	private final CopyOnWriteArrayList<ConcurrentSkipListSet<String>> fullMatch = new CopyOnWriteArrayList<ConcurrentSkipListSet<String>>(); 
		
	public ConcurrentMatchHandler() {
		// nothing to do
	}
	
	public void reset(){
		refMap.get().clear();
		ConcurrentMap<String, Set<String>> newValue = UtilsCollect.newConcurrentMap();
		refMap.set(newValue);
//		ctgIdx.clear();
	}
	
//	public void registerContigSet(Set<String> contigSet){
//		int i = 0;
//		for(String s : contigSet){
//			ctgIdx.put(s, i++);
//			fullMatch.add(new ConcurrentSkipListSet<String>());
//		}		
////		refMap.get().putIfAbsent(contig, new ConcurrentSkipListSet<String>());		
//	}
	
	public void registerContig(String contig){
		refMap.get().putIfAbsent(contig, new ConcurrentSkipListSet<String>());		
	}
	
	public Set<String> getReadsForContig(String contig){
		return refMap.get().get(contig);
	}
	
	/**
	 * Only insert Read, if the Contig identifier was registered before
	 * 
	 * @param contig Contig identifier
	 * @param readId Read identifier cleaned and without Strand / Direction information
	 * @return 
	 */
	public boolean addMatch(String contig, String readId){
		Set<String> set = refMap.get().get(contig);
		if(null != set){
			set.add(readId);
			return true;
		}
		return false;
	}
	
}
